<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\OfContractService;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\View;

/**
 * 合同管理-控制器
 * @author 牧羊人
 * @since: 2021/12/21
 * Class Ofcontract
 * @package app\admin\controller
 */
class Ofcontract extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2021/12/21
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model            = new \app\admin\model\OfContract();
        $this->service          = new OfcontractService();
        $this->OfcompanyService = new \app\admin\service\OfCompanyService();
        $this->OfCompanyModel   = new \app\admin\model\OfCompany();
    }

    /**
     * 数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function index()
    {
        $company_id = input("company_id", 0);
        View::assign("company_id", $company_id);
        return parent::index(); // TODO: Change the autogenerated stub
    }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 牧羊人
     * @since 2020/7/2
     */
    public function edit()
    {
        if (IS_POST) {
            $company_id = input('company_id','');
            if(!$company_id){
                return message('请选择正确的客户',false);
            }
            $contract_no = input('contract_no','');
            if(!$contract_no){
                return message('合同编号未填写',false);
            }
            $id = input('id','');
            $check_no = $this->model->where('mark',1)->where('id','<>',$id)->where('contract_no',$contract_no)->value('id');
            if($check_no){
                return message('合同编号不能重复',false);
            }
            // $result = $this->service->edit();
            // return $result;

            // 获取参数
            $argList = func_get_args();
            // 查询条件
            $data = isset($argList[0]) ? $argList[0] : [];
            // 是否打印SQL
            $is_sql = isset($argList[1]) ? $argList[1] : false;
            if (!$data) {
                $data = request()->param();
            }
            //新增 type
            $remark_arr = [];
            if ($data['type'] == 1) {

                for ($i = 0; $i < 4; $i++) {
                    $index        = "type_remark1_" . $i;
                    $remark_arr[] = $data[$index];
                }
            }
            $data['charge_details'] = json_encode($remark_arr);

            //新增standard
            $standard_details = [];
            if ($data['standard'] == 1) {
                $standard_details[] = $data['standard_details_0'];
                $standard_details[] = $data['standard_details_1'];
            }
            $data['standard_details'] = json_encode($standard_details);

            $error = '';
            $rowId = $this->model->edit($data, $error, $is_sql);
            if ($rowId) {
                return message();
            }
            return message($error, false);

        }
        $info = [];
        $id   = input("get.id", 0);
        if ($id) {
            $info = $this->model->getInfo($id);
            if (!empty($info)) {
                $info['company_name']     = Db::name("of_company")->where("id", $info['company_id'])->value("name");
                $info['charge_details']   = empty($info['charge_details']) ? [] : json_decode($info['charge_details']);
                $info['standard_details'] = empty($info['standard_details']) ? [] : json_decode($info['standard_details']);
            }
        } else {
            $data = func_get_args();
            if (isset($data[0])) {
                foreach ($data[0] as $key => $val) {
                    $info[$key] = $val;
                }
            }
        }
        View::assign("info", $info);
        return $this->render();
    }

    /**
     * 删除单条记录
     * @return array
     * @author 牧羊人
     * @date 2019/2/25
     */
    public function drop()
    {   
        if (IS_POST) {
            $id = input('post.id');

            $pa_info = Db::name("of_patent")->where("contract_id", $id)->where('mark', 1)->find();
            if (!empty($pa_info)) {
                return message("还有关联专利数据,无法删除", false);
            }
            $pr_info = Db::name("of_project")->where("contract_id", $id)->where('mark', 1)->find();
            if (!empty($pr_info)) {
                return message("还有关联项目数据,无法删除", false);
            }
            $info = $this->model->getInfo($id);
            if ($info) {
                $result = $this->model->drop($id);
                if ($result !== false) {
                    return message();
                }
            }
            return message($this->model->getError(), false);
        }
    }

    /**
     * 批量删除记录
     * @return array
     * @author 牧羊人
     * @date 2019/2/25
     */
    public function batchDrop()
    {   
        $msg = '';
        if (IS_POST) {
            $ids = explode(',', $_POST['id']);
            //批量删除
            $num = 0;
            foreach ($ids as $key => $val) {
                $pa_info = Db::name("of_patent")->where("contract_id", $val)->where('mark', 1)->find();
                if (!empty($pa_info)) {
                    $msg .= "\n ID:".$val." : 还有关联专利无法删除";
                    continue;
                }
                $pr_info = Db::name("of_project")->where("contract_id", $val)->where('mark', 1)->find();
                if (!empty($pr_info)) {
                    $msg .= "\n ID:".$val." : 还有关联项目无法删除";
                    continue;
                }
                $res = $this->model->drop($val);
                if ($res !== false) {
                    $num++;
                }
            }

            return message('本次共选择' . count($ids) . "个条数据,删除" . $num . "个".$msg,);
        }
    }

    /**
     * @date: 2022/1/4 0002
     * @describe:打包下载
     */
    // public function download()
    // {
    //     $filename = $this->request->param("filename");

    //     $path = app()->getRootPath() . 'public/uploads/';
    //     if (is_file($path . $filename)) {
    //         $msg = message("执行成功", true, ['filename' => $filename]);
    //     } else {
    //         $msg = message("暂无数据", false);
    //     }
    //     return json_encode($msg);
    // }

    /**
     * 
     */
    public function rename(){


        $famlePath = $_GET['url'];
        // $ext=substr(strrchr($famlePath, '.'), 1);
        // $new_filename = $compony_name."的合同.".$ext;

        $file_dir = ROOT_PATH . 'public' . '/' . 'uploads' . '/' . "$famlePath";    // 下载文件存放目录
            
        // 检查文件是否存在
        if (! file_exists($file_dir) ) {
            exit();
        }else{
            // 打开文件
            $file1 = fopen($file_dir, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:".filesize($file_dir));
            Header("Content-Disposition: attachment;filename=" . $_GET['name']);
            ob_clean();     // 重点！！！
            flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file1, filesize($file_dir));
            fclose($file1);
            exit();
        }
    } 

    /**
     * 批量添加数据列表页
     * https://blog.csdn.net/lmy1998/article/details/118420437 参考此处 原先导入的模式 因为7.4的原因语法报错
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function batch_import()
    {
        if (IS_POST) {
            $param = request()->param();
            $data  = $this->getUrl($param['url']);
            if (!$data) {
                return message();
            }
            return message($data, false);
        } else {
            return $this->render();
        }

    }

    /**
     * 客户必填 合同编号必填
     * 查重
     * 不能为空
     * 如果错误则不让导入
     */
    public function getUrl($path)
    {
        ini_set('max_execution_time', '0');
        $msg = '';

        $file = 'uploads/' . $path;
        if (!is_file($file)) {
            return "\n 请选择文件";
        }
        $data = $this->OfcompanyService->readFile($file, 1);
        if (!$data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $save_data = [];
        foreach ($data as $k => $item) {
            //判断模板是否正确
            if ($k == 1) {
                if ($item[0] !== '客户名称' || $item[1] !== '签订日期' || $item[2] !== '合同编号' || $item[3] !== '合同金额' || $item[5] !== '已收部分款项') {
                    $msg .= "\n 模板错误请选择正确的模板进行导入";
                    return $msg;
                }
                continue;
            }
            //跳过空行
            $is_empty = '';
            foreach ($item as $key => $value) {
                $is_empty .= $value;
            }
            if (!$is_empty) {
                continue;
            }
            //对必填的列判断
            if (empty($item[0])) {
                $msg .= "\n" . $k . "行:客户名称未填写";
                return $msg;
            }
            if (empty($item[2])) {
                $msg .= "\n" . $k . "行:合同编号未填写";
                return $msg;
            }
            if ($item[4]) {
                if (!in_array($item[4], ['全款', '部分款项'])) {
                    $msg .= "\n" . $k . "行:收费情况应该填写（填写 全款或已收部分款项）";
                    return $msg;
                }
            }
            if ($item[10]) {
                if (!in_array($item[10], ['仅收代理费', '包含官费'])) {
                    $msg .= "\n" . $k . "行:收费标准应填写（填写 仅收代理费或包含官费）";
                    return $msg;
                }
            }
            //客户名称必填 且需要查询出id
            $company_id = $this->OfCompanyModel->where('name', $item[0])->where('mark', 1)->value('id');

            if (!$company_id) {
                $msg .= "\n" . $k . "行:客户未匹配";
                return $msg;
            }

            //优先查重表格
            $excel_map = [
                ['contract_no' => $item[2]],
            ];
            $is_excel_set = $this->OfcompanyService->checkDuplicate($excel_map, $save_data);
            if ($is_excel_set) {
                $msg .= "\n" . $k . "行:重复(当前导入的表格中存在相同的合同编号)";
                return $msg;
            }
            //查重 创建合同一定有合同编号的吧
            $map = [
                ['mark', '=', 1],
                ['contract_no', '=', $item[2]],
            ];

            $is_set = $this->model->where($map)->value('id');
            if ($is_set) {
                $msg .= "\n" . $k . "行:重复（数据库中合同编号已存在）";
                return $msg;
            }
            // $type     = $item[4] == '部分款项' ? 1 : 0;
            $type     = '';
            if($item[4] == '部分款项'){
                $type = 1;
            }elseif ($item[4] == '全款') {
                $type = 0;
            }

            // $standard = $item[10] == '包含官费' ? 1 : 0;
            $standard = $item[10] == '包含官费' ? 1 : 0;
            $standard = '';
            if($item[10] == '包含官费'){
                $standard = 1;
            }elseif ($item[10] == '仅收代理费') {
                $standard = 0;
            }

            $item6 = $this->OfcompanyService->changDate($item[6]);
            $item7 = $this->OfcompanyService->changDate($item[7]);
            $item8 = $this->OfcompanyService->changDate($item[8]);

            $charge_details   = json_encode([$item[5], $item6, $item7, $item8]);
            $standard_details = json_encode([$item[11], $item[12]]);

            $signing_date = $this->OfcompanyService->changDate($item[1]);

            $save_data[] = [
                'company_id'       => $company_id,
                'signing_date'     => $signing_date,
                'contract_no'      => $item[2],
                'amount'           => $item[3],
                'type'             => $type,
                'standard'         => $standard,
                'third_fee'        => $item[9],
                'charge_details'   => $charge_details,
                'standard_details' => $standard_details,
                'create_time'      => time(),
                'update_time'      => time(),
                'remark'           => $item[13],
            ];
        }
        if (!$save_data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $res = $this->model->saveAll($save_data);
        if ($res) {
            $msg .= "";
        } else {
            $msg .= "\n 插入未知错误";
        }
        return $msg;
    }

    public function excel()
    {
        ini_set('max_execution_time', '0');
        $param = request()->param();
        // 查询要导出的数据
        $map = [
            ['mark', '=', 1],
        ];
        if ($param['company_id']) {
            $map[] = ['company_id', '=', $param['company_id']];
        }
        if ($param['contract_no']) {
            $map[] = ['contract_no', 'like', '%' . $param['contract_no'] . '%'];
        }
        $admin_id = session("adminId");
        if($admin_id != 1){            
            $wh_or = [];
            $wh_or[] = ["service_id","=",$admin_id];
            $wh_or[] = ["agent_id","=",$admin_id];
            $wh_or[] = ["peer_id","=",$admin_id];
            $arr_ids = Db::name("of_company")->where('mark',1)->where(function($query) use($wh_or){$query->whereOr($wh_or);})->column("id");
            if(!empty($arr_ids)){
                $map[] = ['company_id', 'in', $arr_ids];            
            }
        }
        $head = [
            ['title' => '客户名称', 'width' => 50],
            ['title' => '签订日期', 'width' => 15],
            ['title' => '合同编号', 'width' => 15],
            ['title' => '合同金额', 'width' => 15],
            ['title' => '收费情况', 'width' => 15],
            ['title' => '已收部分款项', 'width' => 20],
            ['title' => '第一笔到款时间', 'width' => 50],
            ['title' => '第二笔到款时间', 'width' => 15],
            ['title' => '第三笔到款时间', 'width' => 15],
            ['title' => '第三方费用', 'width' => 15],
            ['title' => '收费标准', 'width' => 15],
            ['title' => '申请费', 'width' => 15],
            ['title' => '授权费', 'width' => 15],
            ['title' => '备注', 'width' => 15],
        ];

        $data = $this->model->where($map)->order('id desc')->select();

        $new_data = [];
        foreach ($data as $key => $v) {
            $tmp = [];
            //客户名称 名称获取
            $name = Db::name("of_company")->where("id", $v['company_id'])->value('name');
            //收费情况
            if(!$v['type']){
                $type = '';
            }else{
                $type  = $v['type'] == 1 ? '部分款项' : '全款';
            }
            //已收部分款项 和第一二三笔
            if(empty($v['charge_details'])){
                $charge_details = [];
            }else{
                $charge_details = json_decode($v['charge_details'],true);
            }
            while(count($charge_details) < 4){
                $charge_details[] = '';
            }
            
            if(!$v['standard']){
                $standard = '';
            }else{
                //收费标准  收费标准 ：0 仅收代理费 1 包含官费
                $standard = $v['standard'] == 0 ?  '仅收代理费' : '包含官费';
            }

            if(empty($v['standard_details'])){
                $standard_details = [];
            }else{
                $standard_details = json_decode($v['standard_details'],true);
            }

            while(count($standard_details) < 2){
                $standard_details[] = '';
            }

            $tmp[] = $name;
            $tmp[] = $v['signing_date'];
            $tmp[] = $v['contract_no'];
            $tmp[] = $v['amount'];
            $tmp[] = $type;
            $tmp[] = $charge_details[0];
            $tmp[] = $charge_details[1];
            $tmp[] = $charge_details[2];
            $tmp[] = $charge_details[3];
            $tmp[] = $v['third_fee'];
            $tmp[] = $standard;
            $tmp[] = $standard_details[0];
            $tmp[] = $standard_details[1];
            $tmp[] = $v['remark'];

            $new_data[] = $tmp;
        }
        $fileName = '合同(' . date("Y-m-d H:i:s") . ')';
        $this->OfcompanyService->exportExcel($head, $new_data, $fileName);
    }
}
